package com.ruoyi.network.websocket;

import java.net.URI;
import java.net.URISyntaxException;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.ruoyi.network.edge.EdgeHelper;

//import com.jxtech.video.bean.CmsIpcDev;
//import com.jxtech.video.service.CmsIpcDevService;
//import com.jxtech.video.util.Constant;
//import com.jxtech.video.websocket.client.AudidoWsClient;

import lombok.extern.slf4j.Slf4j;

/**
 * 定时任务
 */
@Component
@Slf4j
public class EdgeWsJob {
	@Value("${network.edge.id}") // 云边协同客户端id
	private String id;
	@Value("${network.edge.name}") // 云边协同客户端名称
	private String name;
	@Value("${network.edge.ip}") // 云边协同客户端ip
	private String ip;
	@Value("${network.edge.wsUrl}") // 云边协同服务器端websocket
	private String wsUrl;
	private EdgeWsClient edgeWsClient;

	@PostConstruct
	private void init() {
		try {
			connect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 热重启时部分资源(线程池、外部连接等)不一定能正常关闭,需要通过@PreDestroy手动关闭处理
	// 从Debug线程情况中可判断是否有关闭,若未关闭数量将一直增加
	@PreDestroy
	public void destroy() {
		if(edgeWsClient != null) {
			edgeWsClient.close();
			edgeWsClient = null;
		}
		
	}

	@Scheduled(cron = "0/25 * * * * ?")
	public void execute() throws Exception {
		if (edgeWsClient != null && edgeWsClient.isClosed()) {
			edgeWsClient.close();
			connect();
		}
		edgeWsClient.heart();
	}

	/**
	 * @throws URISyntaxException
	 */
	private void connect() throws URISyntaxException {
		edgeWsClient = new EdgeWsClient(new URI(wsUrl), id, name, ip);
		edgeWsClient.connect();
	}
}
